import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { inject, observer, Observer } from 'mobx-react';
import { ChatStore } from '../../store/ChatStore';
import { SystemStore } from '../../store/SystemStore'
import { ChatItem, ChatGrOrFrType } from '../../interface/IChat';
import { MainStore } from '../../store/MainStore';
import { AutoSizer } from 'react-virtualized/dist/es/AutoSizer';
import { List as VList, ListRowProps } from 'react-virtualized/dist/es/List';
import { List, Tabs } from 'antd';

import { ChartItem } from '../../component/chatItem/ChatItem';
import { notShowContent } from '../../net/Const';
import './ChatMessage.less';
import UserSearch from '../../component/UserSearch/UserSearch';
const { TabPane } = Tabs;

// import {listForceUpdate} from './../../service/listForceUpdate'
export interface IChartMessageProps extends RouteComponentProps {
}

export interface IChartMessageState {
    selectedChatId: string | null;
    selectedServicedChatId:string |null;
    showChatTab?:boolean;
}
interface IChartMessagePropsWithStore extends IChartMessageProps {
    chatStore: ChatStore,
    mainStore: MainStore,
    systemStore:SystemStore,
}
@inject('chatStore', 'mainStore','systemStore')
@observer
export default class ChartMessage extends React.Component<IChartMessageProps, IChartMessageState> {
    constructor(props: IChartMessageProps) {
        super(props);
        this.state = {
            selectedChatId: null,
            selectedServicedChatId:null,
            showChatTab:false
        }
        setTimeout(()=>{
            this.setState({
                //showChatTab:true
            })
        },3000)
    }
    get injected() {
        return this.props as IChartMessagePropsWithStore
    }
    delChart = (chat: ChatItem) => {
        this.injected.chatStore.delChart(chat)
    }
    noReadMsgNumber =(chatId: string) =>{
        const noReadMsg = this.injected.chatStore.unReadMsgs.get(chatId + '');
        if(Array.isArray(noReadMsg) && noReadMsg.length > 0){
            return noReadMsg.length
        }else{
            return 0
        }
    }
    get currentServicedChatData(){
        const data = this.injected.chatStore.getCurrentChat('service')
        return data?data:{id:-1}
    }
    updateFoceList = () => {
        this.listDom && this.listDom.forceUpdateGrid()
    }
    // componentDidMount(){
    //     //增加列表强制更新的回调 因为虚拟列表的刷新需要强制刷新来更新数据
    //     listForceUpdate.setChatListUpdateFun(listForceUpdate.chatListKey,this.updateFoceList)
    // }
    // componentWillUnmount(){
    //     //去除列表强制更新的回调
    //     listForceUpdate.removeChatListUpdateFun(listForceUpdate.chatListKey)
    // }
    listChatItemClick = (chatId: string, tag:string = 'default') => {
        this.setState({ selectedChatId: chatId });
        setTimeout(() => {
            this.injected.chatStore.changeSelectChat && this.injected.chatStore.changeSelectChatByTag(chatId, tag )
        }, 0);
    }
    listDom:any=null 
    _renderServicedChatList = ( listChats:ChatItem[] ) => {
        const data:any /**chatItem */ = this.injected.chatStore.getCurrentChat('service')
        let selectedId = ''
        if( data ){
            selectedId = data.id
        }
        if( !listChats || listChats.length == 0){
            return <div className="chat-list-group-wrapper cha-lis-img">
                 <img src={require('./../../assets/image/image01.png')} alt="chart"/>
                <span className='cha-lis-txt'> 暂无接待客户 </span>
            </div>
        }
    	return  <div className="chat-list-group-wrapper">
            { listChats.map((item,index) => {
                return (
                    <div key={index}>
                    <span
                    onClick={()=> {
                        this.listChatItemClick(item.id,'service')
                    }}
                    // : this.injected.chatStore.currentChatData.id === item.id ? 'selected' 
                    className = { this.injected.chatStore.currentChatData.id == item.id ? 'selected': ''}
                >    
                    {/* <span>id:{item.id},sid:{item.isServicingUserId}</span> */}
                    
                    <ChartItem
                        statusDictionary = {this.injected.systemStore.systemDictinary}
                        toTop={this.injected.chatStore.setTop}
                        toListTop={this.injected.chatStore.setListTop}
                        toManualRead={this.injected.chatStore.setManualRead}
                        toNotice={this.injected.chatStore.setNotice}
                        
                        delChart={this.delChart}
                        context={false}
                        {...item}
                        noRead={this.noReadMsgNumber(item.id)}
                        isGroup={item.type == ChatGrOrFrType.group}
                        selected={this.injected.chatStore.currentChatData.id == item.id}
                    />
                </span>
                    </div>
                )
                
            }) }
        </div>
    }
    _renderChatList = ( listChats:ChatItem[] ) => {
        if( !listChats || listChats.length == 0){
            return <div className="chat-list-group-wrapper cha-lis-img">
                 <img src={require('./../../assets/image/image01.png')} alt="chart"/>
                <span className='cha-lis-txt'> 暂无聊天记录 </span>
            </div>
        }
        return  <div className="chat-list-group-wrapper">
                { listChats.map((item,index) => {
                    
                    return (
                        <div key={index}>
                        <span
                        onClick={()=> {
                            this.listChatItemClick(item.id)
                        }}
                        // : this.injected.chatStore.currentChatData.id === item.id ? 'selected' 
                        className = {this.state.selectedChatId === item.id ? 'selected': ''}
                    >
                        
                        {/* <span>id:type:{item.userType}</span> */}
                        {/* <span>id:{item.id}，to:{(item as any).to},from:{(item as any).from}sid:{item.isServicingUserId}</span> */}
                        <ChartItem
                            statusDictionary = {this.injected.systemStore.systemDictinary}
                            toTop={this.injected.chatStore.setTop}
                            toListTop={this.injected.chatStore.setListTop}
                            toManualRead={this.injected.chatStore.setManualRead}
                            toNotice={this.injected.chatStore.setNotice}
                            
                            delChart={this.delChart}
                            context={true}
                            {...item}
                            noRead={this.noReadMsgNumber(item.id)}
                            isGroup={item.type == ChatGrOrFrType.group}
                            selected={this.injected.chatStore.currentChatData.id == item.id}
                        />
                    </span>
                        </div>
                    )
                    
                }) }
                {/* <AutoSizer>{({ width, height }) => (
                    <List 
                        ref={ref => this.listDom = ref}
                        style={{paddingRight:'12px'}}
                        rowHeight={70}
                        width={width}
                        height={height}
                        overscanRowCount={10}
                        rowCount={listChats.length}
                        rowRenderer = {({ ...props }) => (
                            <Observer key = {props.key}>
                            {() => this._rowRenderer({ ...props })}
                            </Observer>
                        )}
                    />
                )}
                </AutoSizer> */}
            </div>
    	 
    }
    _renderList = () => {
    	let listChats = this.injected.chatStore.chats.filter(item => item.lastContent != notShowContent);
        const filterText = this.injected.mainStore.filterTxt;
        
        if( filterText ){
            listChats = listChats.filter(item => {
                let name = ''
                if(item.type == ChatGrOrFrType.group){
                    name = item.name;
                }else{
                    name = item.name
                }
                if( !name && item.extendInfo ){
                    name = item.extendInfo.name || item.extendInfo.nickname;
                }
                return name.indexOf(filterText) > -1
            })
        }
        console.log('render chats', listChats)
		return (
            <div className='message-wrapper'>
                {
                    this.state.showChatTab ? <Tabs defaultActiveKey="1" onChange={()=>{}}>
                    <TabPane tab="Tab 1" key="1">
                        { this._renderChatList(listChats)}
                    </TabPane>
                    <TabPane tab="Tab 2" key="2">
                    Content of Tab Pane 2
                    </TabPane>
                </Tabs>:this._renderChatList(listChats)
                }
            </div>
			
		);	
    }
    _rowRenderer = ({ key, index, style }:ListRowProps) => {
        let listChats = this.injected.chatStore.chats.filter(item => item.lastContent != notShowContent);
        const filterText = this.injected.mainStore.filterTxt;
        
        if( filterText ){
            listChats = listChats.filter(item => {
                let name = ''
                if(item.type == ChatGrOrFrType.group){
                    name = item.name;
                }else{
                    name = item.name
                }
                if( !name && item.extendInfo ){
                    name = item.extendInfo.name || item.extendInfo.nickname;
                }
                return name.indexOf(filterText) > -1
            })
        }

		const item = listChats[index];
		return (
            <div className='message-wrapper'>
                {
                    item?<div key={key} style={style}>
                    <span 
                        onClick={()=> this.listChatItemClick(item.id)}
                        className = {this.injected.chatStore.currentChatData.id == item.id?'selected':''}
                    >
                        <ChartItem
                            toTop={this.injected.chatStore.setTop}
                            toListTop={this.injected.chatStore.setListTop}
                            toNotice={this.injected.chatStore.setNotice}
                            toManualRead={this.injected.chatStore.setManualRead}
                            delChart={this.delChart}
                            {...item}
                            noRead={this.noReadMsgNumber(item.id)}
                            isGroup={item.type == ChatGrOrFrType.group}
                            selected={this.injected.chatStore.currentChatData.id == item.id}
                        />
                    </span>
                </div>:null
                }
            </div>
			
		);
    };
    // chatList: ChatItem[];
    public render() {
        const { chatStore } = this.injected;
        let listChats = chatStore.chats.filter(item => item.lastContent != notShowContent);
        let listServicedChats = chatStore.servicesChats;
        const filterText = this.injected.mainStore.filterTxt;
        if( filterText ){
            listChats = listChats.filter(item => {
                let name = ''
                name = item.name;
                return name.includes(filterText)
            })
            listServicedChats = listServicedChats.filter(item => {
                let name = ''
                name = item.name;
                return name.includes(filterText)
            })
        }
        const showTabs = this.injected.systemStore.user.isService();
        const newServicedUserLength = chatStore.servicesChats.length - chatStore.currentServicedLength
        return (
            <>
            <div className='chart-list chart-list-chat ant-tabs-bar'>
                <div className='dragbox'></div>
                <UserSearch></UserSearch>
                {
                    showTabs ? <Tabs defaultActiveKey="2" onChange={(value)=>{
                        if( value == '2'){
                            chatStore.currentServicedLength = chatStore.servicesChats.length
                        }
                    }}>
                        <TabPane tab="所有聊天" key="1">
                            { this._renderChatList(listChats)}
                        </TabPane>
                        <TabPane tab={<div className="tab-title" key='2'>
                            { newServicedUserLength >0 ? <span className="hot"></span> :null}
                            <span>正在接待</span>
                        </div>} key="2" >
                            { this._renderServicedChatList(listServicedChats)}
                        </TabPane>
                    </Tabs>:this._renderChatList(listChats)
                }
                

                
                
            </div>
                
            </>
        );
    }
}
